package org.example.filter;

import com.alibaba.fastjson.JSON;
import org.example.common.BaseContxt;
import org.example.domain.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public final static AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
        String requestURI = servletRequest1.getRequestURI();
        String[] urls = {"/employee/login", "/backend/**", "/employee/loginOut", "/front/**", "/user/sendMsg", "/user/login", "/backend", "/", "/gitee/del"};
        if (check(requestURI, urls)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (servletRequest1.getSession().getAttribute("employee") != null) {
            BaseContxt.setId((Long) servletRequest1.getSession().getAttribute("employee"));
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (servletRequest1.getSession().getAttribute("user") != null) {
            BaseContxt.setId((Long) servletRequest1.getSession().getAttribute("user"));
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        servletResponse1.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean check(String requestUrl, String[] urls) {
        for (String url :
                urls) {
            boolean match = pathMatcher.match(url, requestUrl);
            if (match) {
                return true;
            }
        }
        return false;
    }
}

